package com.razorfish.configuration.entities 
{
	import com.razorfish.configuration.ConfigService;
	/**
	 * ...
	 * @author derek
	 */
	public class Item extends SingleConfigObject
	{
		public var properties:Vector.<ItemProperty>;
		public var className:String;
		
		public function Item(data:XML, parent:Group)
		{
			super(data, parent);
			this.className = data.name();
			this.simpleName = data.attribute(ConfigService.ITEM_ID_PROP_NAME);
			this.uniqueName = parent.uniqueName + " - " + simpleName;
			SingleConfigObject.registerItem(this);
			init();
		}
		
		private function init():void
		{
			properties = new Vector.<ItemProperty>();
			for each (var attr:XML in originalData.attributes())
			{
				if (attr.name() == ConfigService.ITEM_ID_PROP_NAME) continue;
				properties.push(new ItemProperty(attr, this));
			}
			
			for each (var ele:XML in originalData.children())
			{
				if (ele.name() == ConfigService.ITEM_ID_PROP_NAME) continue;
				properties.push(new ItemProperty(ele, this));
			}
			
			if (properties.length < 1) 
			{
				isValueReady = true;
				properties = null;
			}
		}
		
		override public function tryGetValue():void 
		{
			if (properties == null) return;
			for each(var prop:ItemProperty in properties)
			{
				prop.tryGetValue();
				if (!prop.isValueReady)
					return;
			}
			
			var classDef:Class = ConfigService.instance.getType(className);
			if (classDef != null)
			{
				var obj:Object = new classDef();
				for each (var p:ItemProperty in properties)
				{
					obj[p.propName] = p.value;
				}
				_value = obj;
				isValueReady = true;
			}
			else
			{
				throw new Error("not good");
			}
		}
		
		public override function get hasDirectValue():Boolean
		{
			if (super.hasDirectValue) return true;
			else
			{
				if (properties == null) return true;
				else
				{
					for each (var obj:ItemProperty in properties)
					{
						if (!obj.hasDirectValue)
						{
							return false;
						}
					}
					
					return true;
				}
			}
		}
	}

}